<script lang="ts">
  import { onMount } from "svelte";
  import {
    sendMessage,
    onMessage,
    subscribe,
    unsubscribe,
  } from "tauri-plugin-libp2p-signal-api";

  let message = "";
  let msgList: string[] = [];

  async function onSendMessage() {
    await sendMessage(message);
  }

  onMount(async () => {
    let handle = onMessage((message: string) => {
      msgList = [...msgList, message];
    });

    let topic = "12345";
    await subscribe(topic);

    return async () => {
      await unsubscribe(topic);
      handle.then(() => {});
    };
  });
</script>

<div>
  <div class="row">
    <input
      id="message-input"
      placeholder="Enter a message..."
      bind:value={message}
    />
    <button on:click={onSendMessage}> Send Message </button>
  </div>
  <p>{message}</p>
  <textarea bind:value={msgList} />
</div>

<style>
  textarea {
    width: 100%;
    height: 200px;
  }
</style>
